package cn.edu.cdtu.healthserver.servlet;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.edu.cdtu.healthserver.domain.Choose;
import cn.edu.cdtu.healthserver.domain.Question;
import cn.edu.cdtu.healthserver.domain.QuestionSet;
import cn.edu.cdtu.healthserver.domain.Test;
import cn.edu.cdtu.healthserver.domain.TestLog;
import cn.edu.cdtu.healthserver.domain.UserInformation;
import cn.edu.cdtu.healthserver.service.ChooseLogService;
import cn.edu.cdtu.healthserver.service.ChooseService;
import cn.edu.cdtu.healthserver.service.LoginControl;
import cn.edu.cdtu.healthserver.service.QuestionService;
import cn.edu.cdtu.healthserver.service.TestLogService;
import cn.edu.cdtu.healthserver.service.impl.ChooseLogServiceImplementation;
import cn.edu.cdtu.healthserver.service.impl.ChooseServiceImplementation;
import cn.edu.cdtu.healthserver.service.impl.QuestionServiceImplementation;
import cn.edu.cdtu.healthserver.service.impl.TestLogServiceImplementation;
import cn.edu.cdtu.healthserver.utils.ConnectUtil;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

/**
 * Servlet implementation class QuestionServletForClient
 */
@WebServlet("/QuestionServletForClient")
public class QuestionServletForClient extends HttpServlet {
	private static final long serialVersionUID = 1L;
    private QuestionService questionService;
    private ChooseService chooseService;
    private TestLogService testLogService;
    private ChooseLogService chooseLogService;
    private Gson gson;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public QuestionServletForClient() {
        super();
        // TODO Auto-generated constructor stub
        questionService = new QuestionServiceImplementation();
        chooseService = new ChooseServiceImplementation();
        testLogService = new TestLogServiceImplementation();
        chooseLogService = new ChooseLogServiceImplementation();
        gson = new Gson();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		String option = request.getParameter(
				ConnectUtil.HealthTestPargrams.Option.HEALTH_TEST_OPTION);
		if(ConnectUtil.HealthTestPargrams.Option.OptionValue
				.HEALTH_TEST_OPTION_GET_QUESTION_SET.equals(option)){
			getQuestionSets(request, response);
		}else if(ConnectUtil.HealthTestPargrams.Option.OptionValue
				.HEALTH_TEST_OPTION_SUBMIT_ANSWER.equals(option)){
			submitAnswer(request, response);
		}
	}
	/**
	 * 
	 * @Title: getQuestionSets 
	 * @Description: TODO
	 * @return void
	 * @throws 
	 *
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void getQuestionSets(HttpServletRequest request, 
			HttpServletResponse response) throws IOException{
		String testJson = request.getParameter(
				ConnectUtil.HealthTestPargrams.Pargram.SELECT_TEST);
		Test test = gson.fromJson(testJson, Test.class);
		List<Question> questions = questionService.getQuestions(test, false);
		List<QuestionSet> questionSets = new ArrayList<QuestionSet>();
		for ( Question question : questions) {
			questionSets.add(new QuestionSet(
					question, 
					chooseService.getChooses(question, false)));
		}
		response.setContentType(ConnectUtil.ContentTypeString.jSON_STRING);
		PrintWriter writer = response.getWriter();
		writer.print(gson.toJson(questionSets));
		writer.flush();
		writer.close();
	}
	/**
	 * 
	 * @Title: submitAnswer 
	 * @Description: TODO
	 * @return void
	 * @throws 
	 *
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void submitAnswer(HttpServletRequest request, 
			HttpServletResponse response) throws IOException{
		UserInformation loginUser = LoginControl.getLoginedUser(request);
		OutputStream writer = response.getOutputStream();
		if(loginUser != null){
			String testJson = request.getParameter(
					ConnectUtil.HealthTestPargrams.Pargram.SELECT_TEST);
			Test test = gson.fromJson(testJson, Test.class);
			String answerJson = request.getParameter(
					ConnectUtil.HealthTestPargrams.Pargram.QUESTION_ANSWER);
			List<Choose> chooses = gson.fromJson(answerJson, 
					new TypeToken<List<Choose>>(){}.getType());
			TestLog testLog = testLogService.createTestLog(
					loginUser, test);
			for(Choose choose:chooses){
				chooseLogService.createChooseLog(testLog, choose);
			}
			response.setContentType(ConnectUtil.ContentTypeString.jSON_STRING);
			writer.write(ConnectUtil.HealthTestPargrams
					.Result.SUBMIT_SUCCESS.getBytes());
		}else{
			writer.write(ConnectUtil.HealthTestPargrams
					.Result.SUBMIT_FAIL.getBytes());
		}
		writer.flush();
		writer.close();
	}
}
